package com.google.memoryofaplace;

import java.util.Date;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.memoryofaplace.model.TBAdmins;

public class BLAdmins {

	public static JSONObject createAdmin(String arg0, int arg1)
			throws JSONException {
		JSONObject jReturn = new JSONObject();
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			TBAdmins TBAdmin = new TBAdmins(arg0, arg1);
			pm.makePersistent(TBAdmin);
			pm.close();
			jReturn.put("status", General.OK);
			jReturn.put("date", General.formatDate(new Date()));
			jReturn.put("codAdmin", TBAdmin.getCodAdmin());
		} catch (Exception e) {
			jReturn = new JSONObject();
			jReturn = General.returnError(e.getMessage());
		}
		return jReturn;
	}

	public static long getAdminUser(String userName) {
		long result = -1;
		try {
			DatastoreService datastoreService = DatastoreServiceFactory
					.getDatastoreService();
			Query q = new Query("TBAdmins");
			q.addFilter("user", FilterOperator.EQUAL, userName);
			Entity e = datastoreService.prepare(q).asSingleEntity();
			result=  (Long) e.getProperty("type");
		} catch (Exception e) {
			System.out.print("error:" + e.getMessage());
		}
		
		return result;
	}

	public static JSONObject getAdminUsers() throws JSONException {
		JSONArray aAdminUsers = new JSONArray();
		DatastoreService datastoreService = DatastoreServiceFactory
				.getDatastoreService();
		Query locationQuery = new Query("TBAdmins");

		JSONObject jAdminUsers = new JSONObject();
		jAdminUsers.put("status", General.OK);
		jAdminUsers.put("date", General.formatDate(new Date()));
		for (Entity location : datastoreService.prepare(locationQuery)
				.asIterable()) {
			JSONObject jAdminUser = new JSONObject();
			jAdminUser.put("user", location.getProperty("user"));
			jAdminUser.put("type", location.getProperty("type"));
			jAdminUser.put("code", location.getKey().getId());

			aAdminUsers.put(jAdminUser);
		}
		jAdminUsers.put("results", aAdminUsers);
		return jAdminUsers;
	}

	public static boolean existsAdminUser(String user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		javax.jdo.Query q = pm.newQuery(TBAdmins.class);
		q.setFilter("user == userParam");
		q.declareParameters("String userParam");
		q.setUnique(true);
		TBAdmins admin = (TBAdmins) q.execute(user);
		q.closeAll();
		return (admin != null);
	}
}
